package com.manbearpig.todue;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

/**
 * Crfeates an activity to show the google map
 * @author Andre Giron
 *
 */
public class HelloGoogleMapsActivity extends MapActivity
{
	String street;
	String city;
	String state;
	String zip;
	String location;
	MapController controller;
	MapView mapView;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //example code for dealing with intents and stuff
        Bundle bundle = this.getIntent().getExtras();
        //this.filterDate = (String)bundle.getString("filterDate");
        street = (String)bundle.getString("Street");
        city = (String)bundle.getString("City");
        state = (String)bundle.getString("State");
        zip = (String)bundle.getString("Zip");

        location = street + " " + city + " " + state + " " + zip;
        setContentView(R.layout.main);

        mapView = (MapView) findViewById(R.id.mapview);
        controller = mapView.getController();
        mapView.setBuiltInZoomControls(true);
        
        showAddress();
    }    
    
    /**
     * Shows a pin at an address based on the input address. 
     */
    public void showAddress()
    {
    	
    	JSONObject jo = this.getLocationInfo(location);
    	GeoPoint p=this.getLatLong(jo);
    	Toast.makeText(getBaseContext(), 
    	                        p.getLatitudeE6() / 1E6 + "," + 
    	                        p.getLongitudeE6() /1E6 , 
    	                        Toast.LENGTH_SHORT).show();
    	
    	controller.setCenter(p);
    	List<Overlay> listOverlays = mapView.getOverlays();
    	listOverlays.clear();
    	
    	HelloItemizedOverlay dp = new HelloItemizedOverlay(this.getResources().getDrawable(R.drawable.pin), this);
    	dp.addOverlay(new OverlayItem(p,null,null));
    	
    	mapView.invalidate();
    	
    	//Here is how you would add a new address. 
    	//Georgia Tech 
    	JSONObject jo2 = this.getLocationInfo("225 North Ave NW, Atlanta, GA 30332");
    	GeoPoint tech = this.getLatLong(jo2);
    	//Georgia Tech Hotel 
    	JSONObject jo3 = this.getLocationInfo("800 Spring St NW, Atlanta, GA 30308");
    	GeoPoint hotel = this.getLatLong(jo3);
    	//Alumni Association
    	JSONObject jo4 = this.getLocationInfo("190 North Ave NW, Atlanta, GA 30313");
    	GeoPoint aa = this.getLatLong(jo4);

    	
    	//Here is how you add the overlay. 
    	//We should set the first string to the name of the task, and the second one to the description
    	//when you click the pin for a long time an AlertDialog appears and displays the information. 
    	//Would be great to use for our todos, just loop through the addresses every time that the map is loaded. 
    	dp.addOverlay(new OverlayItem(tech, "Georgia Tech", "This is where Georgia Tech is located."));
    	dp.addOverlay(new OverlayItem(hotel, "Georgia Tech Hotel", "Come stay at the luxurious Georgia Tech Hotel"));
    	dp.addOverlay(new OverlayItem(aa, "Georgia Tech Alumni Association", "Remember to join the Alumni Association when you graduate."));
    	
    	
    	listOverlays.add(dp);
    	mapView.invalidate();
   

    	
    }
    
    
    public static JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


            response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return jsonObject;
    }

    
    public static GeoPoint  getLatLong(JSONObject jsonObject) {

        Double lon = new Double(0);
        Double lat = new Double(0);

        try {

            lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

            lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        } catch (Exception e) {
            e.printStackTrace();

        }

        return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
    }

    @Override
    protected boolean isRouteDisplayed()
    {
        return false;
    }
}